<?php

class Model_Category extends Joob_Db_Table	{
	
	protected $key = "id";
	
	protected $db = "categories";
	
	public function editName()	{
		return $this->edit('name');
	}
	
	public function editImage()	{
		return $this->edit('image');
	}
	
	public function loadProducts()	{
		$rs = $this->search('parent_id = '.$this->id, "id, name, image");
		if (count($rs) > 0)	{
			return array('type'=>'category', 'data'=>$rs);
		}
		
		$model = new Model_Product();
		$rs = $model->search("category_id = ".$this->id, "id, name, image, description");
		$result = array();
		foreach ($rs as $row) {
			if ($row->description == null)	{
				$row->description = '';
			}
			$result[] = $row;
		}
		return array('type'=>'product', 'data'=>$result);
	}
	
	public function addNew()	{
		$this->since = time();
		return $this->insert('name, parent_id, description, since');
	}
	
	public static function loadLeafCategories()	{
		$model = new Model_Category();
		return $model->search('id not in (select parent_id from categories)', 'id, name');
	}
	
	public static function loadAllCategories()	{
		$model = new Model_Category();
		return $model->search('', 'id, name', '50', 'id ASC');
	}
	
	public static function getInitialCategories()	{
		$model = new Model_Category();
		$rs = $model->search('parent_id=0','id, name', 50, 'name ASC');
		$result = array();
		foreach ($rs as $row)	{
			$id = $row->id;
			$category = new Model_Category();
			$rs2 = $category->search("parent_id=$id", "id, name");
			$row->categories = $rs2;
			$result[] = $row;
		}
		return $result;
	}
	
	public function getInfo()	{
		return array('id'=>$this->id, 'name'=>$this->name, 'image'=>$this->image);
	}
}

?>